package com.world.business.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.world.business.dict.domain.vo.DictDataVO;
import com.world.business.dict.service.IDictDataService;
import com.world.business.user.domain.UserEquipment;
import com.world.business.user.domain.query.*;
import com.world.business.user.domain.vo.UserEquipmentVO;
import com.world.business.user.mapper.UserEquipmentMapper;
import com.world.business.user.service.IUserEquipmentService;
import com.world.business.weapon.domain.Weapon;
import com.world.business.weapon.mapper.WeaponMapper;
import com.world.common.enumeration.DelFlagEnum;
import com.world.common.exception.BusinessException;
import com.world.common.security.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户装备 服务实现类
 * </p>
 *
 * @author 邓驴
 * @since 2023-07-27
 */
@Service
public class UserEquipmentServiceImpl extends ServiceImpl<UserEquipmentMapper, UserEquipment> implements IUserEquipmentService {

    @Resource
    private WeaponMapper weaponMapper;
    @Resource
    private IDictDataService dictDataService;

    @Override
    public IPage<UserEquipmentVO> getPage(IPage<UserEquipment> page, UserEquipmentPageRequest request) {
        IPage<UserEquipmentVO> result = this.baseMapper.getPage(page, request);
        List<UserEquipmentVO> records = result.getRecords();
        records.forEach(i -> {
            DictDataVO dictDataVO = dictDataService.get(Long.valueOf(i.getLevel()));
            if (BeanUtil.isNotEmpty(dictDataVO)) {
                i.setLevel(dictDataVO.getLabel());
            }
        });
        return result;
    }

    @Override
    public Long add(UserEquipmentAddRequest request) {

        LambdaQueryWrapper<Weapon> lambdaQuery = Wrappers.lambdaQuery(Weapon.class);
        lambdaQuery.select(Weapon::getId, Weapon::getUniqueness);
        lambdaQuery.eq(Weapon::getDelFlag, DelFlagEnum.NORMAL.getCode());
        lambdaQuery.eq(Weapon::getId, request.getRelationId());
        Weapon weapon = weaponMapper.selectOne(lambdaQuery);
        if (BeanUtil.isEmpty(weapon)) {
            throw new BusinessException(HttpStatus.HTTP_BAD_REQUEST, "装备不存在！");
        }

        if (weapon.getUniqueness().equals(1)) {
            //判断装备是否存在被使用
            LambdaQueryWrapper<UserEquipment> queryWrapper = Wrappers.lambdaQuery(UserEquipment.class);
            queryWrapper.select(UserEquipment::getId);
            queryWrapper.eq(UserEquipment::getDelFlag, DelFlagEnum.NORMAL.getCode());
            queryWrapper.eq(UserEquipment::getRelationId, request.getRelationId());
            UserEquipment userEquipment = this.baseMapper.selectOne(queryWrapper);
            if (BeanUtil.isNotEmpty(userEquipment)) {
                throw new BusinessException(HttpStatus.HTTP_BAD_REQUEST, "装备已被使用！");
            }
        }

        UserEquipment userEquipment = BeanUtil.copyProperties(request, UserEquipment.class);
        if (userEquipment.getNum() == null || weapon.getUniqueness().equals(1)) {
            userEquipment.setNum(1);
        }
        if (userEquipment.getIntegrity() == null) {
            userEquipment.setIntegrity(1.0);
        }
        userEquipment.setCreateBy(SecurityUtils.getLoginUser().getName());
        userEquipment.setCreateById(SecurityUtils.getLoginUser().getId());
        userEquipment.setCreateTime(LocalDateTime.now());
        this.baseMapper.insert(userEquipment);
        return userEquipment.getId();
    }

    @Override
    public void delete(Long id) {
        LambdaUpdateWrapper<UserEquipment> updateWrapper = Wrappers.lambdaUpdate(UserEquipment.class);
        updateWrapper.eq(UserEquipment::getId, id);
        updateWrapper.set(UserEquipment::getDelFlag, DelFlagEnum.DELETE.getCode());

        updateWrapper.set(UserEquipment::getUpdateBy, SecurityUtils.getLoginUser().getName());
        updateWrapper.set(UserEquipment::getUpdateById, SecurityUtils.getLoginUser().getId());
        updateWrapper.set(UserEquipment::getUpdateTime, LocalDateTime.now());

        this.baseMapper.update(null, updateWrapper);
    }

    @Override
    public void numChangeById(UserEquipmentNumChangeByIdRequest request) {

        LambdaQueryWrapper<UserEquipment> queryWrapper = Wrappers.lambdaQuery(UserEquipment.class);
        queryWrapper.select(UserEquipment::getId, UserEquipment::getNum);
        queryWrapper.eq(UserEquipment::getDelFlag, DelFlagEnum.NORMAL.getCode());
        queryWrapper.eq(UserEquipment::getId, request.getId());
        UserEquipment userEquipment = this.baseMapper.selectOne(queryWrapper);

        update(userEquipment, request.getNum());
    }

    @Override
    public void numChange(UserEquipmentNumChangeRequest request) {

        LambdaQueryWrapper<UserEquipment> queryWrapper = Wrappers.lambdaQuery(UserEquipment.class);
        queryWrapper.select(UserEquipment::getId, UserEquipment::getNum);
        queryWrapper.eq(UserEquipment::getDelFlag, DelFlagEnum.NORMAL.getCode());
        queryWrapper.eq(UserEquipment::getUserId, request.getUserId());
        queryWrapper.eq(UserEquipment::getRelationId, request.getRelationId());
        UserEquipment userEquipment = this.baseMapper.selectOne(queryWrapper);

        update(userEquipment, request.getNum());
    }

    private void update(UserEquipment userEquipment, Integer num) {
        if (BeanUtil.isEmpty(userEquipment)) {
            throw new BusinessException("数据不存在！");
        }

        Weapon weapon = weaponMapper.selectById(userEquipment.getRelationId());
        if (weapon.getUniqueness().equals(1)) {
            throw new BusinessException("装备数量不支持变更！");
        }

        if (userEquipment.getNum() < 0 || userEquipment.getNum() + num < 0) {
            throw new BusinessException("变更数量超出用户持有数量！");
        }

        LambdaUpdateWrapper<UserEquipment> updateWrapper = Wrappers.lambdaUpdate(UserEquipment.class);
        updateWrapper.eq(UserEquipment::getId, userEquipment.getId());
        updateWrapper.set(UserEquipment::getNum, userEquipment.getNum() + num);

        updateWrapper.set(UserEquipment::getUpdateBy, SecurityUtils.getLoginUser().getName());
        updateWrapper.set(UserEquipment::getUpdateById, SecurityUtils.getLoginUser().getId());
        updateWrapper.set(UserEquipment::getUpdateTime, LocalDateTime.now());
        this.baseMapper.update(null, updateWrapper);
    }

    @Override
    public void equipmentLoss(UserEquipmentLossRequest request) {
        this.baseMapper.equipmentLoss(request);
    }

    @Override
    public List<UserEquipmentVO> get(Long userId) {
        List<UserEquipmentVO> records = this.baseMapper.get(userId);
        records.forEach(i -> {
            DictDataVO dictDataVO = dictDataService.get(Long.valueOf(i.getLevel()));
            if (BeanUtil.isNotEmpty(dictDataVO)) {
                i.setLevel(dictDataVO.getLabel());
            }
        });
        return records;
    }


}
